package com.penghaisoft.microwms.producthand.web.controller.intowarehouse;


import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.data.model.ProBarcode;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.ProBarcodeDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IWmsCommonService;
import com.penghaisoft.microwms.product.service.IProBarcodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping(value = "/probarcode/downline/intowh")
@Slf4j
public class ProBarcodeController extends BaseController {

    @Autowired
    private IProBarcodeService proBarcodeService;

    @Autowired
    private IWmsCommonService wmsCommonService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;//注入对象

    /**
     * 新增记录
     *
     * @param proBarcode
     * @return
     */
    @PostMapping("c")
    public TransResult create(ProBarcode proBarcode) {
        proBarcode.preInsert();
        Resp resp = proBarcodeService.create(proBarcode);
        return fromResp(resp);
    }

    /**
     * 删除记录（逻辑删除active_flag=0)
     *
     * @param proBarcode
     * @return
     */
    @PostMapping("d")
    public TransResult delete(ProBarcode proBarcode) {
        proBarcode.preUpdate();
        Resp resp = proBarcodeService.delete(proBarcode);
        return fromResp(resp);
    }

    /**
     * 查询列表
     *
     * @param pager
     * @return
     */
    @PostMapping("list")
    public TransResult list(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, ProBarcode proBarcode) {
        Pager<ProBarcode> result = proBarcodeService.findListByCondition(page, rows, proBarcode);
        return success(result);
    }

    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    @GetMapping("r/{id}")
    public TransResult queryById(@PathVariable String id) {
        ProBarcode proBarcode = proBarcodeService.findById(id);
        return success(proBarcode);
    }

    /**
     * 修改记录
     *
     * @param proBarcode
     * @return
     */
    @PostMapping("u")
    public TransResult update(ProBarcode proBarcode) {
        proBarcode.preUpdate();
        Resp resp = proBarcodeService.update(proBarcode);
        return fromResp(resp);
    }

    /**
     * @param proOrderInSnDto
     * @return HandResp
     * @Title scanBarcode
     * @Description 扫码入库
     * @author luoteng
     * @date 2018年6月7日:上午10:03:52
     */
    @PostMapping("scan")
    public HandResp scanBarcode(@RequestBody ProBarcodeDto proBarcodeDto) {
        HandResp resp = new HandResp();

        String regex = "^\\d+(\\.\\d+)?";

        if (proBarcodeDto.getWeight() == null || proBarcodeDto.getWeight().equals("")) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("请输入 重量！");
            return resp;
        } else if (!proBarcodeDto.getWeight().toString().matches(regex)) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("请输入正确的数字！");
            return resp;
        }


        String key = Constant.PRO_DOWNLINEIN_PREFIX + proBarcodeDto.getBarcode();


        if (proBarcodeDto.getBarcode() == null || proBarcodeDto.getBarcode().equals("")) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("请扫描条码！");
            return resp;
        }

        if (stringRedisTemplate.hasKey(key)) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("当前条码正在处理中，请不要重复扫描！");
            return resp;
        } else {
            stringRedisTemplate.opsForValue().set(key, "1", Constant.PRO_HAND_LOST_MINUTES, TimeUnit.MINUTES);//写入对象，并设置失效时间
            try {
                TransResult result = proBarcodeService.downlineScanBarcode(proBarcodeDto);
                resp.setCode(result.getCode());
                resp.setMsg(result.getMsg());
                resp.setList(result.getList());
            } catch (RuntimeException e) {
                resp.setCode(Constant.FAIL);
                resp.setMsg(e.getMessage());
            } finally {
                stringRedisTemplate.delete(key);//删除对象
            }
        }

        return resp;
    }

    /**
     * @return HandResp
     * @Title: returns
     * @Description: 获取批次号
     * @author yanggm
     * @date 2018年11月2日
     */
    @PostMapping("batchcode")
    public HandResp returns() {
        HandResp resp = new HandResp();
        resp.setCode(Constant.SUCCESS);
        String batchCode = wmsCommonService.getProShortSeq5(Constant.SEQ_PREFIX_SHORT_TH,
                Constant.SEQ_PREFIX_SHORT_REDIS_PRO_XSC, 1).get(0);
        resp.setValue(batchCode);
        return resp;
    }

    /**
     * @return HandResp
     * @Title: returnsScan
     * @Description: 退货入库扫码
     * @author yanggm
     * @date 2018年11月1日
     */
    @PostMapping("returns")
    public HandResp returnsScan1(@RequestBody ProBarcodeDto proBarcodeDto) {
        HandResp resp = new HandResp();
        resp.setCode(Constant.SUCCESS);
//        if (null == proBarcodeDto.getBatchCode()) {
//            resp.setCode(Constant.FAIL);
//            resp.setMsg("请先获取批次号");
//            return resp;
//        }

        String key = Constant.RETURN_PREFIX + proBarcodeDto.getBarcode();
        if (stringRedisTemplate.hasKey(key)) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("当前条码正在处理中，请不要重复扫描！");
            return resp;
        } else {
            stringRedisTemplate.opsForValue().set(key, "1", Constant.PRO_HAND_LOST_MINUTES, TimeUnit.MINUTES);//写入对象，并设置失效时间
            try {
                TransResult result = proBarcodeService.returnsScan(proBarcodeDto);
                resp.setCode(result.getCode());
                resp.setMsg(result.getMsg());
                resp.setList(result.getList());
            } catch (Exception e) {
                resp.setCode(Constant.FAIL);
                resp.setMsg(e.getMessage()==null?"出现异常":e.getMessage());
            } finally {
                stringRedisTemplate.delete(key);//删除对象
            }
        }
        return resp;
    }
    
    /**
    * @Title: complete 
    * @Description: 退货扫码确认 
    * @author yanggm 
    * @date 2019年1月3日
     */
    @PostMapping("returns2")
    public HandResp returnsScan2(@RequestBody ProBarcodeDto proBarcodeDto){
    	HandResp resp = new HandResp();
    	String regex = "^\\d+(\\.\\d+)?";

        if (proBarcodeDto.getWeight() == null || proBarcodeDto.getWeight().equals("")) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("请输入 重量！");
            return resp;
        } else if (!proBarcodeDto.getWeight().toString().matches(regex)) {
            resp.setCode(Constant.FAIL);
            resp.setMsg("请输入正确的数字！");
            return resp;
        }
         
    	String key = Constant.RETURN_PREFIX + proBarcodeDto.getBarcode();
    	if(stringRedisTemplate.hasKey(key)){
    		resp.setCode(Constant.FAIL);
    		resp.setMsg("请等" + Constant.PRO_HAND_LOST_MINUTES + "分钟再操作！");
    	}else{
			stringRedisTemplate.opsForValue().set(key, "1", Constant.PRO_HAND_LOST_MINUTES, TimeUnit.MINUTES);//写入对象，并设置失效时间
			TransResult result = new TransResult();
			try{
				result = proBarcodeService.returnsScan(proBarcodeDto);
				resp.setCode(result.getCode());
		        resp.setMsg(result.getMsg());
		        resp.setList(result.getList());
			}catch(RuntimeException e){
				resp.setCode(Constant.FAIL);
				resp.setMsg(e.getMessage());
			}finally{
				stringRedisTemplate.delete(key);//删除对象  
			}
    	}
		return resp;
    }

}
